﻿namespace ChinaUnicom.Parser
{
    using Avatar.Log;
    using ChinaUnicom.Models;
    using ChinaUnicom.Parser.Parsers;
    using HtmlAgilityPack;
    using System;
    using System.Collections.Generic;
    using System.Linq;

    class HtmlParser : IHtmlParser
    {
        Dictionary<ItemType, IItemsParser> parsers;

        public HtmlParser()
        {
            parsers = new Dictionary<ItemType, IItemsParser>();

            parsers.Add(ItemType.Client, new ClientParser());
            parsers.Add(ItemType.FeeHistory, new FeeHistoryParser());
            parsers.Add(ItemType.Fee, new FeeParser());
            parsers.Add(ItemType.Package, new PackageParser());
            parsers.Add(ItemType.Point, new PointParser());
            parsers.Add(ItemType.Product, new ProductParser());
        }
        
        public ItemCollection Parse(string html, ItemType type)
        {
            if (!parsers.ContainsKey(type))
            {
                throw new NotSupportedException();
            }

            return parsers[type].Parse(html);
        }

        public string Failed(string html)
        {
            string tips = "系统异常,操作失败！";

            try
            {
                HtmlDocument doc = new HtmlDocument();
                doc.LoadHtml(html);

                var span = doc.DocumentNode.Descendants("span").FirstOrDefault(x => x.InnerText.Contains("【温馨提示】"));

                if (span != null)
                {
                    var tipsNode = span.ParentNode.Descendants("span").FirstOrDefault(x => x.InnerText.Contains("&nbsp;&nbsp;&nbsp;&nbsp;"));
                    if (tipsNode != null)
                    {
                        tips = tipsNode.InnerText
                            .Replace("&nbsp;", string.Empty)
                            .Replace("\t", string.Empty)
                            .Replace("\r", string.Empty)
                            .Replace("\n", string.Empty)
                            .InnerTextTrim();
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.Error(ex);
            }

            return tips;
            /*
	        <span>【温馨提示】</span>
	        <br />
	        <span>&nbsp;&nbsp;&nbsp;&nbsp;系统异常,操作失败！</span>

            <span>【温馨提示】</span>
            <br />
            <span>&nbsp;&nbsp;&nbsp;&nbsp;系统异常,操作失败！系统正忙，请稍后再试。</span>

            <span>【温馨提示】</span>
            <br />
            <span>&nbsp;&nbsp;&nbsp;&nbsp;尊敬的用户，每月最后一天22:00至次日09:00是系统出账期，请您在出账期之后进行操作。</span>
            */
        }
    }
}
